package org.jeecg.modules.app.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.app.constant.AppConstant;
import org.jeecg.modules.app.entity.AppClient;
import org.jeecg.modules.app.entity.AppPushConfig;
import org.jeecg.modules.app.mapper.AppPushConfigMapper;
import org.jeecg.modules.app.service.IAppClientService;
import org.jeecg.modules.app.service.IAppPushConfigService;
import org.jeecg.modules.app.vo.PushConfigVO;
import org.jeecg.modules.rental.entity.RentalConfig;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description: 推送配置
 * @Author: jeecg-boot
 * @Date:   2024-12-17
 * @Version: V1.0
 */
@Service
@RequiredArgsConstructor
public class AppPushConfigServiceImpl extends ServiceImpl<AppPushConfigMapper, AppPushConfig> implements IAppPushConfigService {

    private final IAppClientService appClientService;

    private final CacheManager cacheManager;

    @Override
    public IPage<AppPushConfig> selectJoinPage(Page page, Wrapper wrapper) {
        IPage<AppPushConfig> pageList = baseMapper.selectJoinPage(page, wrapper);
        if(ObjectUtil.isNotEmpty(pageList) && ObjectUtil.isNotEmpty(pageList.getRecords())){
            Set<Long> clientIds = pageList.getRecords().stream().map(AppPushConfig::getClientId).collect(Collectors.toSet());
            List<AppClient> appClientList = appClientService.listByIds(clientIds);
            pageList.getRecords().stream().forEach(item->{
                Optional<AppClient> clientOptional = appClientList.stream().filter(a-> a.getId().equals(item.getClientId())).findFirst();
                clientOptional.ifPresent(a-> item.setClientName(a.getName()));
            });
        }
        return pageList;
    }

    @Override
    public PushConfigVO get(String platform) {
        Cache cache = cacheManager.getCache(AppConstant.APP_PUSH_CONFIG_CACHE);
        String key = TenantContext.getTenant() + ":" + platform;;
        PushConfigVO config = cache.get(key, PushConfigVO.class);
        if(oConvertUtils.isEmpty(config)){
            config = baseMapper.selectOneNoTenant(new QueryWrapper<RentalConfig>()
                    .eq("platform_type", platform));
            if(oConvertUtils.isNotEmpty(config)){
                cache.put(key, config);
            }
        }
        return config;
    }

    @Override
    public AppPushConfig add(AppPushConfig entity) {
        if(this.saveOrUpdate(entity)){
            if(ObjectUtil.isNotEmpty(entity.getClientId())){
                AppClient appClient = appClientService.getById(entity.getClientId());
                if(ObjectUtil.isNotEmpty(appClient)){
                    Cache cache = cacheManager.getCache(AppConstant.APP_PUSH_CONFIG_CACHE);
                    String key = TenantContext.getTenant() + ":" + appClient.getPlatformType();
                    cache.put(key, entity);
                }
            }
        }
        return entity;
    }

    @Override
    public AppPushConfig edit(AppPushConfig entity) {
        if(this.saveOrUpdate(entity)){
            if(ObjectUtil.isNotEmpty(entity.getClientId())){
                AppClient appClient = appClientService.getById(entity.getClientId());
                if(ObjectUtil.isNotEmpty(appClient)){
                    Cache cache = cacheManager.getCache(AppConstant.APP_PUSH_CONFIG_CACHE);
                    String key = TenantContext.getTenant() + ":" + appClient.getPlatformType();
                    cache.put(key, entity);
                }
            }
        }
        return entity;
    }

    @Override
    public Boolean deleteById(String id) {
        AppPushConfig entity = this.getById(id);
        if(ObjectUtil.isNotEmpty(entity.getClientId())){
            AppClient appClient = appClientService.getById(entity.getClientId());
            if(ObjectUtil.isNotEmpty(appClient)){
                Cache cache = cacheManager.getCache(AppConstant.APP_PUSH_CONFIG_CACHE);
                String key = TenantContext.getTenant() + ":" + appClient.getPlatformType();
                cache.evict(key); // 删除缓存项
            }
        }
        return this.removeById(id);
    }

    @Override
    public Boolean deleteBatch(List<String> ids) {
        List<AppPushConfig> configList = this.listByIds(ids);
        if(ObjectUtil.isNotEmpty(configList)){
            List<Long> idList = configList.stream()
                    .map(AppPushConfig::getId).collect(Collectors.toList());
            List<AppClient> clientList = appClientService.listByIds(idList);
            if(ObjectUtil.isNotEmpty(clientList)){
                Cache cache = cacheManager.getCache(AppConstant.APP_PUSH_CONFIG_CACHE);
                clientList.forEach(item->{
                    String key = TenantContext.getTenant() + ":" + item.getPlatformType();
                    cache.evict(key);
                });
            }
        }
        return this.removeByIds(ids);
    }
}
